package com.itheima.springsecurity;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.SpringSecurityUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


//不用自己调用 框架自动调用
public class SpringSecurityUser implements UserDetailsService {

    @Reference
    private SpringSecurityUserService springSecurityUserService;

    // 根据用户名获取 用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = springSecurityUserService.getByUsername(username);


        if (user == null) {
            // 用户不存在，认证失败
            return null;
        } else {
            Integer id = user.getId();
            //动态为当前用户授权
            List<GrantedAuthority> list = new ArrayList<>();

            // 获取该用户的所有角色
            List<Role> roleList = springSecurityUserService.getByUserId(id);
            if (roleList != null) {
                //为用户添加角色
                for (Role role : roleList) {
                    list.add(new SimpleGrantedAuthority(role.getKeyword()));
                }
                //获取该用户的所有权限
                List<Permission> permissionList = springSecurityUserService.getByRole(roleList);
                // 为用户添加权限
                if (permissionList != null) {
                    for (Permission permission : permissionList) {
                        list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    }
                }
            }


            return new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
        }


    }
}
